import Taro, {Component, useEffect, useState} from '@tarojs/taro'
import {View, Canvas} from '@tarojs/components'
import './index.scss'

type PageState = {}

const defaultProgressStyle = {
  width: 280,
  height: 280,
}

interface ProgressStyle {
  width: number
  height: number
}

type PageStateProps = {
  progress: [number]
  colors: [string]
  canvasStyle?: ProgressStyle
}
type IProps = PageStateProps

interface RoundProgress {
  props: IProps
}
let windowWidth // 可使用窗口宽度
let windowHeight // 可使用窗口高度
let ratio // 根据尺寸动态计算 1px换算成多少rpx

// class RoundProgress extends Component<{}, any> {
function RoundProgress(props) {
  // state = {
  //     width: defaultProgressStyle.width,
  //     height: defaultProgressStyle.height
  // }
  const [width, setWidth] = useState(defaultProgressStyle.width)
  const [height, setHeight] = useState(defaultProgressStyle.height)
  // useEffect(()=>{
  //     if(props){

  //     }
  // },[])
  useEffect(() => {
    Taro.getSystemInfo({
      success: (res) => {
        windowWidth = res.windowWidth
        windowHeight = res.windowHeight
        ratio = 750 / windowWidth
      },
    }).then(() => {
      if (props.canvasStyle) {
        console.log('kkkk', props.canvasStyle)
        // this.setState({width: props.canvasStyle.width, height: props.canvasStyle.height}, ()=>{
        //     this.draw()
        // })
        draw()
        setWidth(() => {
          return props.canvasStyle.width
        })
        setHeight(() => {
          return props.canvasStyle.height
        })
      } else {
        draw()
      }
    })
  }, [])

  const draw = () => {
    console.log('draw', props.progress)
    let that = this
    console.log(that, 'this')
    if (!props.progress) return
    if (props.progress && !props.progress.length) return
    const strokeWidth = 20 / ratio
    const center = width / 2 / ratio
    const r = center - strokeWidth / 2.0
    const ctx = Taro.createCanvasContext('canvasProgress0', that)
    props.progress.map((value, index) => {
      const color = props.colors[index]
      const lineCap = value >= 1 ? 'butt' : 'round'
      value > 0 && drawProgress(ctx, value, r, color, center, strokeWidth, lineCap)
    })
    ctx.draw()
  }
  const drawProgress = (ctx, progress, r, color, center, strokeWidth, lineCap) => {
    ctx.setLineWidth(strokeWidth)
    ctx.setStrokeStyle(color)
    ctx.setLineCap(lineCap)
    ctx.beginPath()
    ctx.arc(center, center, r, -Math.PI / 2, progress * 2 * Math.PI - Math.PI / 2, false) //x,y,半径,开始,结束
    ctx.stroke()
  }

  return (
    <View
      className="progress_box"
      style={'width:' + this.state.width + 'px;' + 'height:' + this.state.height + 'px;'}>
      <Canvas
        style={'width:' + this.state.width + 'px;' + 'height:' + this.state.height + 'px;'}
        className="progress_canvas"
        canvasId={'canvasProgress0'}
      />
    </View>
  )
}

export default RoundProgress
